<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\HeyInfo;
use app\admin\model\DataCountry;
use app\admin\model\DataUnit;
use app\admin\model\Goods;
use app\admin\model\Order;
use app\admin\model\OrderGoods;
use fast\Random;
use fast\Http;
use think\Config;

/**
 * 拉取下属商场系统数据
 */
class Hey extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private $api_version = '1.0';
    private $country_list = false;

    private $errmsg = '';
    private $trans_count = 0;
    private $trans_time = 0;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     * @return [type]
     */
    private function _init() {

    }

    /**
     * 获取商品信息
     * @param  request-int $admin_id   管理员编号
     * @param  request-int $page_index   页码,从0开始
     * @return [type] [description]
     */
    public function trans_goods() {
        $admin_id = $this->request->request('admin_id');
        $page_index = $this->request->request('page_index');

        $this->trans_time = time();

        $res = $this->get_goods_info($admin_id, $page_index);
        if ($res) {
            $hey_info = HeyInfo::where(['admin_id' => $admin_id])->update(['goods_update'=> $this->trans_time]);
            $this->success(__('Trans Success'), ['trans_count' => $this->trans_count]);
        }else{
            $this->error($this->errmsg);
        }
    }

    /**
     * 获取商品信息
     * @param  request-int $admin_id   管理员编号
     * @param  request-int $page_index   页码,从0开始
     * @return [type] [description]
     */
    public function trans_order() {
        $admin_id = $this->request->request('admin_id');
        $page_index = $this->request->request('page_index');

        $this->trans_time = time();

        $res = $this->get_order_info($admin_id, $page_index);
        if ($res) {
            $hey_info = HeyInfo::where(['admin_id' => $admin_id])->update(['order_update'=> $this->trans_time]);
            $this->success(__($this->errmsg), ['trans_count' => $this->trans_count]);
        }else{
            $this->error($this->errmsg);
        }
    }


    /**
     * /
     * @param  boolean $admin_id   [description]
     * @param  boolean $page_index [description]
     * @return [type]              [description]
     */
    private function get_goods_info($admin_id = false, $page_index = false)
    {
        $this->api_version;
        
        $page_index = $page_index?$page_index:0;

        if (!$admin_id) {
            $this->errmsg .= __('Invalid parameters');
            return false;
        }
        $hey_info = HeyInfo::where(['admin_id' => $admin_id])->find();

        if (empty($hey_info)) {
            $this->errmsg .= __('Invalid Admin info');
            return false;
        }
        if (!$hey_info['trans_switch']) {
            $this->errmsg .= __('Invalid trans switch');
            return false;
        }
        if (!$hey_info['shop_url']) {
            $this->errmsg .= __('Invalid shop url');
            return false;
        }

        $api_url = $hey_info['sync_goods_url'];
        if (!$api_url) {
            $this->errmsg .= __('商品同步地址未设置');
        }elseif (!strstr($api_url, '?')) {
            $api_url = $api_url.'?';
        }
        $last_trans_time = $hey_info['goods_update'];
        // $last_trans_time = 0;

        $request_data = array(
            'page_index' => $page_index,
        );
        $request_param = array(
            'last_trans_time' => $last_trans_time,
        );
        $request_param = http_build_query($request_param);

        $request_url = $api_url.'&'.$request_param;

        $this->errmsg = '地址'.$request_url."\n";
        $res = Http::post($request_url, $request_data);

        $goods_model = new Goods;
        $dataCountry_model = new DataCountry;

        $res_json = json_decode($res,true);
        if (isset($res_json['status']) && $res_json['status'] == '1') {
            $goods_data = $res_json['data'];
            $has_next = $res_json['next'] == 'true'?true:false;
            $this->trans_time = $res_json['trans_time'];
            if (!empty($goods_data)) {
            
                $goods_sn_list = array_column($goods_data, 'goods_sn');
                $exist_goods_ids = $goods_model->where('goods_sn','in',$goods_sn_list)->column('id','goods_sn');
                $insert_data = array();
                $update_data = array();
                foreach ($goods_data as $_key => $_row) {
                    $_row['admin_id'] = $admin_id;
                    if (isset($_row['country_name']) && $_row['country_name']) {
                        $_row['country_code'] = $this->get_country_code($_row['country_name']);
                    }
                    if (isset($_row['unit_name']) && $_row['unit_name']) {
                        $_row['unit_code'] = $this->get_unit_code($_row['unit_name']);
                    }

                    if ($goods_id = isset($exist_goods_ids[$_row['goods_sn']])?$exist_goods_ids[$_row['goods_sn']]:false) {
                        $_row['updatetime'] = $this->trans_time;
                        $_row['id'] = $exist_goods_ids[$_row['goods_sn']];
                        
                        $update_data[] = $_row;
                    }else{
                        $_row['createtime'] = $this->trans_time;
                        $_row['guid'] = Random::uuid();
                        /*特殊参数*/
                        $_row['goods_status'] = ($_row['goods_sn'] && $_row['goods_name'] && $_row['goods_price'] && isset($_row['unit_code']) && $_row['unit_code'] && isset($_row['country_code']) && $_row['country_code'])?1:2;
                        $insert_data[] = $_row;
                    }

                }

                if (empty($insert_data) && empty($update_data)) {
                    $this->errmsg .= __('Invalid Data Form');
                    return false;
                }

                if(!empty($insert_data)) $ins_flag = $goods_model->isUpdate(false)->allowField(true)->isAutoWriteTimestamp(true)->saveAll($insert_data);
                if(!empty($update_data)) $ups_flag = $goods_model->isUpdate(true)->allowField(true)->isAutoWriteTimestamp(true)->saveAll($update_data);

                if ($status = (!empty($ins_flag) || !empty($ups_flag))) {
                    $this->trans_count += count($insert_data) + count($update_data);
                    if ($has_next) {
                        $is_end = $this->get_goods_info($admin_id,$page_index+1);
                        return $is_end;
                    }else{
                        return true;
                    }
                }else{
                    $this->errmsg .= __('System DB Save Error');
                    return false;
                }
            } else {
                $this->errmsg .= __('Empty Data Form');
                return true;
            }
        }else{
            $this->errmsg .= __('Data Error:').var_export($res_json, true);
            return false;
        }
    }

    /**
     * 订单信息
     * @param  boolean $admin_id   [description]
     * @param  boolean $page_index [description]
     * @return [type]              [description]
     */
    private function get_order_info($admin_id = false, $page_index = false)
    {
        $this->api_version;
        
        $page_index = $page_index?$page_index:0;

        if (!$admin_id) {
            $this->errmsg .= __('Invalid parameters');
            return false;
        }
        $hey_info = HeyInfo::where(['admin_id' => $admin_id])->find();

        if (empty($hey_info) || !$hey_info['trans_switch'] || !$hey_info['shop_url']) {
            $this->errmsg .= __('Invalid Admin info');
            return false;
        }

        $api_url = $hey_info['sync_order_url'];
        if (!$api_url) {
            $this->errmsg .= __('订单同步地址未设置');
        }elseif (!strstr($api_url, '?')) {
            $api_url = $api_url.'?';
        }
        $last_trans_time = $hey_info['order_update'];
        // $last_trans_time = 0;
        
        $request_data = array(
            'page_index' => $page_index,
        );
        $request_param = array(
            'last_trans_time' => $last_trans_time,
        );
        $request_param = http_build_query($request_param);
        $request_url = $api_url.'&'.$request_param;

        $this->errmsg = '地址'.$request_url."\n";
        $res = Http::post($request_url, $request_data);

        $order_model = new Order;
        $orderGoods_model = new OrderGoods;
        $dataCountry_model = new DataCountry;

        $res_json = json_decode($res,true);
        if (isset($res_json['status']) && $res_json['status'] == '1') {
            $order_data = $res_json['data'];
            $has_next = $res_json['next'] == 'true'?true:false;
            $this->trans_time = $res_json['trans_time'];
            if (!empty($order_data)) {

                $order_sn_list = array_column($order_data, 'order_sn');
                $exist_order_ids = $order_model->where('order_sn','in',$order_sn_list)->where('admin_id',$admin_id)->column('order_id','order_sn');
                $goods_list = array();
                $insert_data = array();
                $update_data = array();
                foreach ($order_data as $_key => $_row) {
                    $_row['admin_id'] = $admin_id;
                    // if (isset($_row['country_name']) && $_row['country_name']) {
                    //     $_row['country_code'] = $this->get_country_code($_row['country_name']);
                    // }
                    // if (isset($_row['unit_name']) && $_row['unit_name']) {
                    //     $_row['unit_code'] = $this->get_unit_code($_row['unit_name']);
                    // }

                    if ($order_id = isset($exist_order_ids[$_row['order_sn']])?$exist_order_ids[$_row['order_sn']]:false) {
                        $_row['updatetime'] = $this->trans_time;
                        $_row['id'] = $exist_order_ids[$_row['order_sn']];
                        // $goods_list[$_row['order_id']] = $_row['goods_list'];
                        $update_data[] = $_row;
                    }else{
                        $_row['createtime'] = $this->trans_time;
                        $_row['guid'] = Random::uuid();
                        if (!isset($_row['goods_list']) || empty($_row['goods_list'])) {
                            $this->errmsg .= __('订单中商品数据缺失');
                            return false;
                        }
                        $goods_list = array_merge_recursive($goods_list,$_row['goods_list']);
                        $insert_data[] = $_row;
                    }

                }

                if (empty($insert_data) && empty($update_data)) {
                    $this->errmsg .= __('Invalid Data Form');
                    return false;
                }

                if(!empty($insert_data)) $ins_flag = $order_model->isUpdate(false)->allowField(true)->isAutoWriteTimestamp(true)->saveAll($insert_data);
                // if(!empty($update_data)) $ups_flag = $order_model->isUpdate(false)->allowField(true)->isAutoWriteTimestamp(true)->saveAll($update_data);

                if ($status = (!empty($ins_flag))) {

                    if (!empty($goods_list)) {
                        // 把数据删除
                        $orderGoods_model->where('order_id','in',array_values($exist_order_ids))->delete();
                        $goods_flag = $orderGoods_model->isUpdate(false)->allowField(true)->isAutoWriteTimestamp(true)->saveAll($goods_list);
                    }

                    $this->trans_count += count($insert_data);
                    if ($has_next) {
                        $is_end = $this->get_order_info($admin_id,$page_index+1);
                        return $is_end;
                    }else{
                        return true;
                    }
                }else{
                    // $this->errmsg .= __('System DB Save Error');
                    // return false;
                    return true;
                }
            } else {
                $this->errmsg .= __('Empty Data Form');
                return true;
            }
        }else{
            $this->errmsg .= __('Data Error:').var_export($res_json, true);
            return false;
        }
    }

    private function get_country_code($name){
        if (!$this->country_list) {
            $dataCountry_model = new DataCountry;
            $this->country_list = $dataCountry_model->column('code','name');
        }
        return isset($this->country_list[$name])?$this->country_list[$name]:'';
    }

    private function get_unit_code($name){
        if (!$this->unit_list) {
            $dataunit_model = new DataUnit;
            $this->unit_list = $dataunit_model->column('code','name');
        }
        return isset($this->unit_list[$name])?$this->unit_list[$name]:'';
    }

}
